package org.goldfish.message_board01.dao;

import org.goldfish.message_board01.entity.MessageDetail;
import org.goldfish.message_board01.util.DatabaseConnectionManager;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MessageDetailDAO extends AbstractDAO {

    public MessageDetailDAO() {
        this.dbManager = new DatabaseConnectionManager();
    }

    public List<String> getMessageContent(int messageId) {
        List<String> contentLines = new ArrayList<>();
        String query = "SELECT content FROM message_detail WHERE message_id = ?";
        try {
            Connection conn = dbManager.getConnection();
            try (
                    PreparedStatement stmt = conn.prepareStatement(query)) {
                stmt.setInt(1, messageId);
                try (ResultSet rs = stmt.executeQuery()) {
                    while (rs.next()) {
                        contentLines.add(rs.getString("content"));
                    }
                }
            }
            dbManager.releaseConnection(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return contentLines;
    }


    private int getNextLineNumber(int messageId) {
        String query = "SELECT MAX(line_number) + 1 AS next_line FROM message_detail WHERE message_id = ?";
        try {
            Connection conn = dbManager.getConnection();
            int nextLine = 1;
            try (
                    PreparedStatement stmt = conn.prepareStatement(query)) {
                stmt.setInt(1, messageId);
                try (ResultSet rs = stmt.executeQuery()) {
                    if (rs.next()) {
                        nextLine = rs.getInt("next_line");
                    }
                }
            }
            dbManager.releaseConnection(conn);
            return nextLine;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 1;
    }

    public boolean insertMessageDetail(MessageDetail detail) {
        String query = "INSERT INTO message_detail (message_id, line_number, content) VALUES (?, ?, ?)";
        try {
            Connection conn = dbManager.getConnection();
            boolean success;
            try (PreparedStatement stmt = conn.prepareStatement(query)) {
                stmt.setInt(1, detail.getMessageId());
                stmt.setInt(2, getNextLineNumber(detail.getMessageId()));
                stmt.setString(3, detail.getContent());
                success = stmt.executeUpdate() > 0;
            }
            dbManager.releaseConnection(conn);
            return success;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
}
